<!DOCTYPE html>
<html lang="zh-CN" data-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ .title }}</title>
    <link href="https://cdn.jsdelivr.net/npm/daisyui@4.12.10/dist/full.min.css" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body class="bg-gray-50">
    {{template "header.html" .}}
    
    <div class="container mx-auto px-4 py-8">
        <!-- 面包屑导航 -->
        <div class="mb-6">
            <div class="flex items-center text-sm text-gray-600">
                <a href="/nodes" class="hover:text-blue-600">节点管理</a>
                <svg class="w-4 h-4 mx-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                </svg>
                <a href="/nodes/{{ .node_id }}" id="breadcrumbNodeName" class="hover:text-blue-600">加载中...</a>
                <svg class="w-4 h-4 mx-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                </svg>
                <span class="text-gray-900 font-medium">NAT规则</span>
            </div>
        </div>

        <!-- 页面标题 -->
        <div class="flex justify-between items-center mb-6">
            <div>
                <h1 class="text-3xl font-bold text-gray-800">NAT端口转发规则</h1>
                <p class="text-gray-600 mt-1" id="nodeNameDisplay">加载中...</p>
            </div>
            <div class="flex gap-2">
                <button onclick="refreshNAT()" class="px-3 py-1.5 text-xs font-medium text-gray-700 bg-gray-50 hover:bg-gray-100 border border-gray-200 rounded-lg transition flex items-center gap-1.5">
                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                    </svg>
                    刷新
                </button>
                <button onclick="showAddNATModal()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition flex items-center gap-2">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                    </svg>
                    添加规则
                </button>
            </div>
        </div>

        <!-- NAT列表 -->
        <div class="bg-white rounded-lg border border-gray-200">
            <div id="natContent" class="p-4 overflow-x-auto">
                <p class="text-center py-8 text-gray-500 text-xs">加载中...</p>
            </div>
        </div>
    </div>

    <!-- 添加NAT模态框 -->
    <dialog id="addNATModal" class="modal">
        <div class="modal-box max-w-2xl">
            <h3 class="font-bold text-base mb-3">添加NAT端口转发规则</h3>
            <form id="addNATForm" class="space-y-3">
                <div class="grid grid-cols-2 gap-4">
                    <div class="form-control">
                        <label class="label"><span class="label-text">容器名称 *</span></label>
                        <select id="natContainer" required class="select select-bordered">
                            <option value="">选择容器</option>
                        </select>
                    </div>
                    <div class="form-control">
                        <label class="label"><span class="label-text">协议 *</span></label>
                        <select id="natProtocol" required class="select select-bordered" onchange="checkNATPort()">
                            <option value="tcp">TCP</option>
                            <option value="udp">UDP</option>
                        </select>
                    </div>
                </div>
                <div class="grid grid-cols-2 gap-4">
                    <div class="form-control">
                        <label class="label"><span class="label-text">外部端口 *</span></label>
                        <input type="number" id="natExternalPort" required min="10000" max="65535" class="input input-bordered" placeholder="10000-65535" onblur="checkNATPort()">
                        <label class="label">
                            <span id="natPortCheck" class="label-text-alt"></span>
                        </label>
                    </div>
                    <div class="form-control">
                        <label class="label"><span class="label-text">内部端口 *</span></label>
                        <input type="number" id="natInternalPort" required min="1" max="65535" class="input input-bordered" placeholder="1-65535">
                    </div>
                </div>
                <div class="form-control">
                    <label class="label"><span class="label-text">描述</span></label>
                    <input type="text" id="natDescription" class="input input-bordered" placeholder="端口用途说明">
                </div>
                <div class="modal-action">
                    <button type="button" onclick="closeNATModal()" class="btn">取消</button>
                    <button type="submit" class="btn btn-primary" id="natSubmitBtn">添加</button>
                </div>
            </form>
        </div>
        <form method="dialog" class="modal-backdrop"><button onclick="closeNATModal()">close</button></form>
    </dialog>

    <script>
        const nodeId = parseInt({{ .node_id }});
        let containersData = [];

        $(document).ready(function() {
            loadNodeInfo();
            loadContainers();
            loadNAT();

            $('#addNATForm').on('submit', function(e) {
                e.preventDefault();
                submitNATForm();
            });
        });

        function loadNodeInfo() {
            $.get(`/api/nodes/${nodeId}`, function(result) {
                if (result.code === 200) {
                    $('#breadcrumbNodeName').text(result.data.name);
                    $('#nodeNameDisplay').text(result.data.name || '未知节点');
                }
            });
        }

        function loadContainers() {
            $.get(`/api/containers/cache?node_id=${nodeId}`, function(result) {
                if (result.code === 200) {
                    containersData = result.data || [];
                }
            });
        }

        function loadNAT() {
            $('#natContent').html('<p class="text-center py-8"><span class="loading loading-spinner loading-md"></span></p>');
            
            $.get(`/api/nat?node_id=${nodeId}`, function(result) {
                if (result.code === 200) {
                    renderNAT(result.data || []);
                } else {
                    $('#natContent').html('<p class="text-center py-8 text-error">加载失败</p>');
                }
            });
        }

        function renderNAT(rules) {
            if (rules.length === 0) {
                $('#natContent').html('<p class="text-center py-8 text-gray-500 text-xs">暂无NAT规则</p>');
                return;
            }

            let html = '<table class="table table-xs w-full"><thead><tr class="bg-gray-50">';
            html += '<th class="text-xs text-gray-600">容器</th><th class="text-xs text-gray-600">协议</th><th class="text-xs text-gray-600">外部端口</th><th class="text-xs text-gray-600">内部端口</th><th class="text-xs text-gray-600">描述</th><th class="text-xs text-gray-600">创建时间</th><th class="text-xs text-gray-600">操作</th>';
            html += '</tr></thead><tbody>';

            rules.forEach(r => {
                html += `<tr class="hover">
                    <td>
                        <a href="/nodes/${nodeId}/containers/${r.container_hostname}" class="font-semibold text-xs text-blue-600 hover:underline">
                            ${r.container_hostname}
                        </a>
                    </td>
                    <td><span class="px-2 py-0.5 text-xs font-medium text-gray-700 bg-gray-100 rounded">${r.protocol.toUpperCase()}</span></td>
                    <td><code class="text-xs font-mono text-gray-700">${r.external_port}</code></td>
                    <td><code class="text-xs font-mono text-gray-700">${r.internal_port}</code></td>
                    <td class="text-xs text-gray-600">${r.description || '-'}</td>
                    <td class="text-xs text-gray-500">${r.created_at ? new Date(r.created_at).toLocaleString('zh-CN') : '-'}</td>
                    <td>
                        <button onclick="deleteNATRule(${r.id})" class="px-2 py-1 text-xs font-medium text-red-700 bg-red-50 hover:bg-red-100 border border-red-200 rounded transition">删除</button>
                    </td>
                </tr>`;
            });

            html += '</tbody></table>';
            $('#natContent').html(html);
        }

        function checkNATPort() {
            const port = $('#natExternalPort').val();
            const protocol = $('#natProtocol').val();
            const containerHostname = $('#natContainer').val();
            
            if (!port || !containerHostname) {
                $('#natPortCheck').html('');
                return;
            }

            // 验证端口范围
            const portNum = parseInt(port);
            if (portNum < 10000 || portNum > 65535) {
                $('#natPortCheck').html('<span class="text-error">✗ 端口必须在 10000-65535 范围内</span>');
                $('#natSubmitBtn').prop('disabled', true);
                return;
            }
            
            $('#natPortCheck').html('<span class="loading loading-spinner loading-xs"></span> 检测中...');
            $('#natSubmitBtn').prop('disabled', true);
            
            $.get(`/api/nat/check?node_id=${nodeId}&hostname=${containerHostname}&port=${port}&protocol=${protocol}`, function(result) {
                if (result.code === 200) {
                    if (result.data && result.data.available) {
                        $('#natPortCheck').html('<span class="text-success">✓ 端口可用</span>');
                        $('#natSubmitBtn').prop('disabled', false);
                    } else {
                        $('#natPortCheck').html('<span class="text-error">✗ 端口已被占用</span>');
                        $('#natSubmitBtn').prop('disabled', true);
                    }
                } else {
                    $('#natPortCheck').html('<span class="text-warning">检测失败: ' + (result.msg || '未知错误') + '</span>');
                    $('#natSubmitBtn').prop('disabled', true);
                }
            }).fail(function() {
                $('#natPortCheck').html('<span class="text-warning">检测失败</span>');
                $('#natSubmitBtn').prop('disabled', true);
            });
        }

        function showAddNATModal() {
            const containers = containersData.map(c => `<option value="${c.hostname}">${c.hostname}</option>`).join('');
            $('#natContainer').html('<option value="">选择容器</option>' + containers);
            $('#natPortCheck').html('');
            $('#natSubmitBtn').prop('disabled', false);
            document.getElementById('addNATModal').showModal();
        }

        function closeNATModal() {
            document.getElementById('addNATModal').close();
            $('#addNATForm')[0].reset();
            $('#natPortCheck').html('');
            $('#natSubmitBtn').prop('disabled', false);
        }

        function submitNATForm() {
            const externalPort = parseInt($('#natExternalPort').val());
            
            // 再次验证端口范围
            if (externalPort < 10000 || externalPort > 65535) {
                showToast('error', '外部端口必须在 10000-65535 范围内');
                return;
            }

            const data = {
                node_id: nodeId,
                container_hostname: $('#natContainer').val(),
                protocol: $('#natProtocol').val(),
                external_port: externalPort,
                internal_port: parseInt($('#natInternalPort').val()),
                description: $('#natDescription').val()
            };

            $('#natSubmitBtn').prop('disabled', true);

            $.ajax({
                url: '/api/nat',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function(result) {
                    if (result.code === 200) {
                        showToast('success', 'NAT规则添加成功');
                        closeNATModal();
                        loadNAT();
                    } else {
                        showToast('error', result.msg);
                        $('#natSubmitBtn').prop('disabled', false);
                    }
                },
                error: function() {
                    showToast('error', '添加失败，请重试');
                    $('#natSubmitBtn').prop('disabled', false);
                }
            });
        }

        function deleteNATRule(id) {
            if (!confirm('确定要删除此NAT规则吗？')) return;
            
            $.ajax({
                url: `/api/nat/${id}`,
                type: 'DELETE',
                success: function(result) {
                    if (result.code === 200) {
                        showToast('success', '删除成功');
                        loadNAT();
                    } else {
                        showToast('error', result.msg);
                    }
                }
            });
        }

        function refreshNAT() {
            loadNAT();
        }

        function showToast(type, message) {
            const colors = {
                'success': 'bg-green-600',
                'error': 'bg-red-600',
                'info': 'bg-blue-600'
            };
            
            const toast = $(`
                <div class="fixed top-4 right-4 ${colors[type] || colors.info} text-white px-6 py-3 rounded-lg shadow-lg z-50">
                    ${message}
                </div>
            `);
            
            $('body').append(toast);
            
            setTimeout(() => {
                toast.fadeOut(300, function() { $(this).remove(); });
            }, 3000);
        }
    </script>

    {{template "footer.html" .}}
</body>
</html>

